const { sqlPromise } = require("../db/sqlPromise");
const bcrypt = require("bcryptjs");
exports.regUser = async (req, res) => {
  //   检测用户名是否被占用
  let sql = "select * from ev_users where username=?";
  let results = await sqlPromise(sql, [req.body.username]);
  if (results.length > 0) {
    return res.send({
      status: 1,
      message: "用户名已存在",
    });
  }
  //   对密码进行加密处理
  let serectPwd = bcrypt.hashSync(req.body.password, 10);
  //   插入新用户
  let insertSql = "insert into ev_users (username,password) values (?,?)";
  let insertRes = await sqlPromise(insertSql, [req.body.username, serectPwd]);
  if (insertRes.affectedRows != 1)
    return res.send({
      status: 1,
      message: "注册失败 未知错误",
    });
  res.send({
    status: 0,
    message: "注册成功",
  });
};
exports.login = async (req, res) => {
  // 根据用户名查询用户的数据
  let sql = "select * from ev_users where username=?";
  let results = await sqlPromise(sql, [req.body.username]);
  if (!results.length) {
    return res.send({
      status: 1,
      message: "该用户不存在",
    });
  }
  //   判断用户输入的密码是否正确
  //   解密
  const compareResult = bcrypt.compareSync(
    req.body.password,
    results[0].password
  );
  //   为true表示相等 false不相等
  if (!compareResult) {
    return res.send({
      status: 1,
      message: "密码错误",
    });
  }
  // 生成JWT的token字符串
  const jwt = require("jsonwebtoken");
  const expressJWT = require("express-jwt");
  const config = require("../config");
  // 密码不能加密  所以对解构赋值出来的密码重新赋值  最后一个是图片头像啥的
  let user = { ...results[0], password: "", user_pic: "" };
  let tokenStr = jwt.sign(user, config.serectKey, { expiresIn: "10h" });
  res.send({
    status: 0,
    message: "登录成功",
    token: "Bearer " + tokenStr,
  });
};
